<template>
    <view class="container">
          <view class="title">聊天</view>
    <!-- z-paging 列表 -->
    <z-paging
      ref="paging"
      refresher-only
      @onRefresh="onRefresh"
    >
      <template #loading>
        <uni-load-more status="loading"></uni-load-more>
      </template>

      <view v-for="s in dataList" :key="s.id" class="item" @click="chatClick(s)">
        <image class="avatar" :src="s.sysUserVo?.avatarUrl || defaultAvatar" mode="cover" />
        <view class="info">
          <view class="name">{{ s.name || s.sysUserVo?.account || ('会话#' + s.id) }}</view>
          <view class="meta">
            {{ s.sessionType === 'group' ? '群聊' : '单聊' }}
            · {{ formatTime(s.lastMessageAt) }}
          </view>
        </view>
      </view>
    </z-paging>  
    </view>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import dayjs from 'dayjs'
import { listMySessions } from '@/api/chat/session'

type Session = any

const paging = ref(null)
const dataList = ref<Session[]>([])
const defaultAvatar = '/static/logo.png'

function getUserId(): number | undefined {
  try {
    const u = uni.getStorageSync('user')
    return u?.id
  } catch { return undefined }
}

function formatTime(t?: string) {
  if (!t) return '无最新消息'
  try {
    return dayjs(t).format('YYYY-MM-DD HH:mm')
  } catch {
    return t
  }
}


const listMySessionsRequest = async (pageNo: number, pageSize: number) => {
    const userId = getUserId()
  if (!userId) {
    // 未登录，提示并跳到登录页
    uni.showToast({ title: '请先登录', icon: 'none' })
    setTimeout(() => {
      uni.switchTab({ url: '/pages/view/MineTab' })
    }, 500)
    paging.value?.complete([], false)
    return
  }
  try {
    const res = await listMySessions({ userId })
    const data = res?.data ?? res
    dataList.value = Array.isArray(data) ? data : (data?.list || [])
    // z-paging 完成回调：第二个参数为是否还有更多数据
    paging.value?.complete(dataList.value, false)
  } catch (e: any) {
    uni.showToast({ title: e?.message || '加载会话失败', icon: 'none' })
    paging.value?.complete([], false)
  }
}

const chatClick = (s: Session) => {
  console.log('chatClick', s)
  try {
    const user = s?.sysUserVo || {}
    const uid = user?.id || s?.ownerId || ''
    const name = user?.nickname || user?.account || s?.name || ''
    const avatar = user?.avatarUrl || ''
    const query = `userId=${encodeURIComponent(uid)}&name=${encodeURIComponent(name)}&avatar=${encodeURIComponent(avatar)}`
    uni.navigateTo({
      url: `/pages/view/UserChatView?${query}`,
      success(res) {
        // 通过 eventChannel 传递完整对象
        // @ts-ignore
        res.eventChannel && res.eventChannel.emit && res.eventChannel.emit('user', { session: s, user })
      }
    })
  } catch (e) {
    // ignore
  }
}

const onRefresh = async () => {
  listMySessionsRequest(1,10)
}

onMounted(() => {
  listMySessionsRequest(1,10)
})

</script>

<style>
.container {
  background: #fff;
}

/* 列表项 */
.item {
  display: flex;
  align-items: center;
  padding: 30rpx 38rpx;
  border-bottom: 1px solid #f2f2f2;
  /* 合适的行高与点击区域 */
  min-height: 100rpx;
  background: #fff;
}
.avatar {
  width: 100rpx;
  height: 100rpx;
  border-radius: 50%;
  background: #f0f0f0;
}
.info {
  margin-left: 30rpx;
  display: flex;
  flex-direction: column;
  justify-content: center;
}
.name {
  font-size: 36rpx;
  color: #333;
  line-height: 55rpx;
}
.meta {
  font-size: 26rpx;
  color: #999;
  margin-top: 6rpx;
  line-height: 40rpx;
}
</style>